package com.atguigu.chapter08;

import com.atguigu.bean.HotItem;
import com.atguigu.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.Date;
import java.util.TreeSet;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/21 14:17
 */
public class Flink03_High_Project_TopN_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> { // 对数据切割, 然后封装到POJO中
                String[] split = line.split(",");
                return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3], Long.parseLong(split[4]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTimestamp())
            )
            .filter(behavior -> "pv".equals(behavior.getBehavior()))
            .keyBy(UserBehavior::getItemId)
            .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(20)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long acc) {
                        return acc + 1;
                    }
                    
                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                },
                // 商品id 窗口结束时间 点击量
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        out.collect(new HotItem(key, elements.iterator().next(), ctx.window().getEnd()));
                    }
                }
            )
            .keyBy(HotItem::getWindowEnd)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                
                private ValueState<TreeSet<HotItem>> setState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    setState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<TreeSet<HotItem>>(
                            "hotItemListState",
                            TypeInformation.of(new TypeHint<TreeSet<HotItem>>() {}))
                        );
                    
                }
                
                @Override
                public void processElement(HotItem hotItem,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    // 状态存储的时候,其实不需要存储所有的元素, 只需要存储已有最大的3个
                    // TreeSet 可以自动排序
                    if (setState.value() == null) {
                        TreeSet<HotItem> hotItems = new TreeSet<>(new Comparator<HotItem>() {
                            @Override
                            public int compare(HotItem o1, HotItem o2) {
                                if (o1.getClickCount().equals(o2.getClickCount())) {
                                    return 1;
                                } else {
                                    return o2.getClickCount().compareTo(o1.getClickCount());
                                }
                            }
                        });
                        setState.update(hotItems);
                        
                        ctx.timerService().registerEventTimeTimer(hotItem.getWindowEnd() + 5000);
                        
                    }
                    
                    TreeSet<HotItem> set = setState.value();
                    set.add(hotItem);
                    
                    if (set.size() > 3) {
                        set.pollLast(); // 删除最后一个
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    TreeSet<HotItem> set = setState.value();
                    
                    StringBuilder sb = new StringBuilder();
                    sb.append("========================\n");
                    for (HotItem hotItem : set) {
                        sb
                            .append("窗口: ")
                            .append(new Date(hotItem.getWindowEnd()))
                            .append(", 商品: ")
                            .append(hotItem)
                            .append("\n");
                    }
                    
                    out.collect(sb.toString());
                    
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
